package com.jgc.stage01.interrupt;

import org.junit.Test;

/**
 * Created by Administrator on 2022/2/10.
 * 注意真正实现一个线程中断还是在线程中去判断 isInterrupted()做出中断
 * interrupted() 作用是测试当前线程是否被中断（检查中断标志），返回一个boolean并清除中断状态，第二次再调用时中断状态已经被清除，将返回一个false
 */
public class Main2 {
    @Test
    //interrupted（）方法测试的是当前线程是否被中断，当前线程！！！当前线程！！！
    // 这里当前线程是main线程，而thread.interrupt(）中断的是thread线程
    //即便是thread.interrupted()也是 获取main方法线程的
    public void test01(){
        MyThread thread=new MyThread();
        thread.start();
        thread.interrupt();
        System.out.println("第一次调用thread.isInterrupted()："+thread.isInterrupted());
        System.out.println("第二次调用thread.isInterrupted()："+thread.isInterrupted());
        //测试interrupted（）函数
        System.out.println("第一次调用thread.interrupted()："+thread.interrupted());//这里是其实是main线程的interrupted() main线程未被中断所以是false
        System.out.println("第二次调用thread.interrupted()："+thread.interrupted());//这里是其实是main线程的interrupted() main线程未被中断所以是false
        System.out.println("thread是否存活："+thread.isAlive());
    }
    @Test
    public void test02(){
        MyThread2 thread=new MyThread2();
        thread.start();
        thread.interrupt();
        System.out.println("第一次调用thread.isInterrupted()："+thread.isInterrupted());
        System.out.println("第二次调用thread.isInterrupted()："+thread.isInterrupted());
        //测试interrupted（）函数
        System.out.println("第一次调用thread.interrupted()："+thread.interrupted());
        System.out.println("第二次调用thread.interrupted()："+thread.interrupted());
        System.out.println("thread是否存活："+thread.isAlive());
    }
}
 class MyThread2 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("i="+(i+1));
            if(this.isInterrupted()){
                System.out.println("通过this.isInterrupted()检测到中断");
                System.out.println("第一个interrupted()"+this.interrupted());
                System.out.println("第二个interrupted()"+this.interrupted());
                break;
            }
        }
        System.out.println("因为检测到中断，所以跳出循环，线程到这里结束，因为后面没有内容了");
    }
}